package com.zjitc.controller;


import com.zjitc.exception.BusinessException;
import com.zjitc.pojo.PageInfo;
import com.zjitc.pojo.Product;
import com.zjitc.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @Author luqi
 * @Date 2025 06 20 21 12
 **/

@Controller
@RequestMapping("/user")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public String listProduct(
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "pageName", defaultValue = "1") int pageName,
            @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
            Model model
    ){
        PageInfo pageInfo = productService.getProductList(keyword,pageName,pageSize);
        model.addAttribute("pageInfo", pageInfo);
        return "/user/list";
    }

    @GetMapping("/add")
    public String addProductFrom(Model model){
        model.addAttribute("product",new Product());
        return "user/add";
    }

    @PostMapping("/add")
    public String addProductSubmit(Product product){

        productService.insert(product);
        return "redirect:/user/list";
    }

    @PostMapping("/delete/{id}")
    public String deleteProduct(@PathVariable Integer id){
        productService.deleteById(id);
        return "redirect:/user/list";
    }

    @GetMapping("/update/{id}")
    public String editProductFrom(@PathVariable Integer id, Model model){
        Product product = productService.selectById(id);
        model.addAttribute("product", product);
        return "user/edit";
    }

    @PostMapping("/update")
    public String editProductSubmit(Product product){
        if (product.getId() == 3){
            throw new BusinessException("这是一个异常测试，修改id为3的数据会跳转error页面");
        }
        productService.update(product);
        return "redirect:/user/list";
    }
}
